﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Twi.COMMON.HTTP;
using System.IO;
using System.Xml.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows;

namespace Twi.COMMON.WPF
{
    public class FileManage
    {
        //系统临时目录
        public static string TemporaryDirectory
        {
            get
            {
                //GetFullPath避免出现路径中出现“~”的省略写法
                return Path.GetFullPath(System.Environment.GetEnvironmentVariable("TEMP")) + @"\";
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="fileID">文件ID</param>
        /// <param name="fileCategory">文件类型</param>
        /// <param name="localPath">文件本地路径</param>
        /// <returns></returns>
        public static bool Upload(Guid fileID, string fileCategory, string localPath, string physicalFileName, Guid fileGroupID = new Guid(), bool isUploadToLocalService = true)
        {
            bool isOK = false;

            //LoadingWaitingFor loadingWaitingFor = new LoadingWaitingFor("正在上传文件，请稍后......");
            //loadingWaitingFor.Topmost = true;
            //loadingWaitingFor.Show();    //跳出等待窗口
            try
            {
                if (File.Exists(localPath))
                {
                    string fileName = Path.GetFileName(localPath);
                    using (Stream stream = File.OpenRead(localPath))
                    {
                        if (stream.Length == 0)
                        {
                            Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("请不用上传空文件！");
                            error.Show();
                            return false;
                        }
                        HttpContent httpContent = HttpContent.Create(stream);
                        //if (!string.IsNullOrEmpty( Twi.COMMON.WPF.Login.UserLogin.CurrentUser.URL) && isUploadToLocalService)
                        //{
                        //    string URL = Twi.COMMON.WPF.Login.UserLogin.CurrentUser.URL;
                        //    using (HttpResponseMessage res = string.Format("" + URL + "GFileMgr/UploadFile?FileID={0}&FileName={1}&FileCategory={2}&FileGroupID={3}&URL={4}", fileID, physicalFileName == "" ? fileName : physicalFileName, fileCategory, fileGroupID, URL).HttpPost(httpContent, true))
                        //    {
                        //        ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                        //        {
                        //            isOK = true;
                        //        });
                        //    }
                        //}
                        //else
                        //{
                        using (HttpResponseMessage res = string.Format("File/UploadFile?FileID={0}&FileName={1}&FileCategory={2}&FileGroupID={3}", fileID, fileName, fileCategory, fileGroupID).HttpPost(httpContent))
                        {
                            ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                            {
                                isOK = true;
                            });
                        }
                        //}
                    }
                }
                else
                {
                    Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("文件不存在:" + localPath);
                    error.Show();
                }
            }
            catch (Exception ex)
            {
                Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("文件上传失败", ex.Message);
                error.Show();
            }
            //finally
            //{
            //    loadingWaitingFor.Close();
            //}
            return isOK;
        }

        public static bool Upload(Guid fileID, string fileCategory, string localPath, Guid fileGroupID = new Guid(), bool isUploadToLocalService = true)
        {
            return Upload(fileID, fileCategory, localPath, "", fileGroupID, isUploadToLocalService);
        }

        #region 上传并加密
        public static bool UploadAndEncrypt(Guid fileID, string fileCategory, string localPath, Guid encryptFileID, string encryptFileCategory)
        {
            bool isOK = false;
            try
            {
                if (File.Exists(localPath))
                {
                    string fileName = Path.GetFileName(localPath);
                    using (Stream stream = File.OpenRead(localPath))
                    {
                        if (stream.Length == 0)
                        {
                            Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("请不用上传空文件！");
                            error.Show();
                            return false;
                        }
                        byte[] fileSrc = new byte[4096];

                        HttpContent httpContent = HttpContent.Create(stream);
                        using (HttpResponseMessage res = string.Format("File/UploadFileAndEncrypt?FileID={0}&FileName={1}&FileCategory={2}&EncryptFileID={3}&EncryptFileCategory={4}", fileID, fileName, fileCategory, encryptFileID, encryptFileCategory).HttpPost(httpContent))
                        {
                            ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                            {
                                isOK = true;
                            });
                        }
                    }
                }
                else
                {
                    Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("文件不存在:" + localPath);
                    error.Show();
                }
            }
            catch (Exception ex)
            {
                Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("文件上传失败", ex.Message);
                error.Show();
            }
            return isOK;
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="newFileID"></param>
        /// <param name="newFileCategory"></param>
        /// <param name="copyFileID"></param>
        /// <returns></returns>
        public static bool Copy(Guid newFileID, string newFileCategory, Guid copyFileID)
        {
            bool isOK = false;

            LoadingWaitingFor loadingWaitingFor = new LoadingWaitingFor("正在拷贝文件，请稍后......");
            loadingWaitingFor.Topmost = true;
            loadingWaitingFor.Show();    //跳出等待窗口
            try
            {
                //if (string.IsNullOrEmpty(Twi.COMMON.WPF.Login.UserLogin.CurrentUser.URL))
                //{
                using (HttpResponseMessage res = string.Format("File/CopyFile?NewFileID={0}&NewFileCategory={1}&CopyFileID={2}", newFileID, newFileCategory, copyFileID).HttpPost())
                {
                    ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                    {
                        isOK = true;
                    });
                }
                //}
                //else {
                //    string URL = Twi.COMMON.WPF.Login.UserLogin.CurrentUser.URL;
                //    using (HttpResponseMessage res = string.Format(URL + "GFileMgr/CopyFile?NewFileID={0}&NewFileCategory={1}&CopyFileID={2}&URL={3}", newFileID, newFileCategory, copyFileID, URL).HttpPost(true))
                //    {
                //        ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                //        {
                //            isOK = true;
                //        });
                //    }
                //}
            }
            catch (Exception ex)
            {
                Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("文件拷贝失败", ex.Message);
                error.Show();
            }
            finally
            {
                loadingWaitingFor.Close();
            }
            return isOK;
        }



        public static bool Upload2(Guid fileID, string fileCategory, string localPath, bool isUploadToLocalService = true)
        {
            bool isOK = false;

            LoadingWaitingFor loadingWaitingFor = new LoadingWaitingFor("正在上传文件，请稍后......");
            loadingWaitingFor.Topmost = true;
            loadingWaitingFor.Show();    //跳出等待窗口
            try
            {
                isOK = Upload(fileID, fileCategory, localPath, new Guid(), isUploadToLocalService);
            }
            catch (Exception ex)
            {
                Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("文件上传失败", ex.Message);
                error.Show();
            }
            finally
            {
                loadingWaitingFor.Close();
            }
            return isOK;
        }


        #region 文件下载
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="fileID"></param>
        /// <param name="savePath">保存路径</param>
        public static string Download(Guid fileID, string savePath)
        {
            LoadingWaitingFor loadingWaitingFor = null;
            try
            {
                XElement xeFileInfo = null;

                HttpQueryString queryString = new HttpQueryString();
                queryString.Add("FileID", fileID.ToString());

                //查询文件信息
                using (HttpResponseMessage res = string.Format("File/GetFileInfo").HttpGet(queryString))
                {
                    ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                    {
                        xeFileInfo = resInfo.ResponseDataMainBody;
                    });
                }
                if (xeFileInfo == null)
                {
                    return "";
                }
                else
                {
                    loadingWaitingFor = new LoadingWaitingFor("正在下载文件，请稍后......");
                    loadingWaitingFor.Topmost = true;
                    loadingWaitingFor.Show();    //跳出等待窗口

                    string newDir = savePath + Guid.NewGuid().ToString();//防止下载重名的文件
                    Directory.CreateDirectory(newDir);

                    savePath = newDir + @"\" + xeFileInfo.Element("FileName").Value + xeFileInfo.Element("Extension").Value;  //文件完整路径及名称
                    if (xeFileInfo.Element("URL").GetValue() == "")
                    {
                        using (HttpResponseMessage res = string.Format("File/Download").HttpGet(queryString))
                        {
                            long length = res.Content.GetLength();
                            if (length > 0)
                            {
                                using (Stream stream = res.Content.ReadAsStream())
                                {
                                    using (FileStream saveStream = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                                    {
                                        byte[] buffer = new byte[length];
                                        int count = 0;
                                        while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                                        {
                                            saveStream.Write(buffer, 0, count);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                return "";
                            }
                        }
                    }
                    else
                    {
                        string URL = xeFileInfo.Element("URL").Value;
                        using (HttpResponseMessage res = string.Format(URL + "GFileMgr/Download").HttpGet(queryString, true))
                        {
                            long length = res.Content.GetLength();
                            if (length > 0)
                            {
                                using (Stream stream = res.Content.ReadAsStream())
                                {
                                    using (FileStream saveStream = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                                    {
                                        byte[] buffer = new byte[length];
                                        int count = 0;
                                        while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                                        {
                                            saveStream.Write(buffer, 0, count);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                return "";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("文件下载失败", ex.Message);
                error.Show();
            }
            finally
            {
                if (loadingWaitingFor != null)
                {
                    loadingWaitingFor.Close();
                }
            }
            return savePath;
        }
        #endregion

        #region 下载文件到系统默认目录
        /// <summary>
        /// 下载文件到系统默认目录
        /// </summary>
        /// <param name="fileID"></param>
        public static string Download(Guid fileID)
        {
            return Download(fileID, TemporaryDirectory);
        }
        #endregion

        #region 打开文件
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="fileID"></param>
        public static void OpenFile(Guid fileID)
        {
            try
            {
                string filePaht = Download(fileID, TemporaryDirectory);
                if (filePaht == "")
                {
                    Tools.GMessageInfo("找不到文件");
                }
                else
                {
                    System.Diagnostics.Process.Start(filePaht);
                }
            }
            catch (Exception ex)
            {
                Twi.COMMON.WPF.Tools.ShowErrorInfo("打开文件失败", ex.Message);
            }
        }
        #endregion

        public static XElement GetFileInfo(Guid fileID)
        {
            XElement xeFileInfo = null;

            HttpQueryString queryString = new HttpQueryString();
            queryString.Add("FileID", fileID.ToString());

            //查询文件信息
            using (HttpResponseMessage res = string.Format("File/GetFileInfo").HttpGet(queryString))
            {
                ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                {
                    xeFileInfo = resInfo.ResponseDataMainBody;
                });
            }
            return xeFileInfo;
        }


        #region 文件下载
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="fileID"></param>
        /// <param name="saveFileName">文件路径+文件名</param>
        public static void DownloadSaveFileName(Guid fileID, string saveFileName)
        {
            LoadingWaitingFor loadingWaitingFor = new LoadingWaitingFor("正在下载文件，请稍后......");
            loadingWaitingFor.Topmost = true;
            loadingWaitingFor.Show();    //跳出等待窗口
            try
            {
                XElement xeFileInfo = null;

                HttpQueryString queryString = new HttpQueryString();
                queryString.Add("FileID", fileID.ToString());

                //查询文件信息
                using (HttpResponseMessage res = string.Format("File/GetFileInfo").HttpGet(queryString))
                {
                    ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                    {
                        xeFileInfo = resInfo.ResponseDataMainBody;
                    });
                }
                if (xeFileInfo != null)
                {
                    using (HttpResponseMessage res = string.Format("File/Download").HttpGet(queryString))
                    {
                        using (Stream stream = res.Content.ReadAsStream())
                        {
                            using (FileStream saveStream = new FileStream(saveFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                            {
                                byte[] buffer = new byte[4096];
                                int count = 0;
                                while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    saveStream.Write(buffer, 0, count);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("文件下载失败", ex.Message);
                error.Show();
            }
            finally
            {
                loadingWaitingFor.Close();
            }
        }
        #endregion

        #region 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="xeFileID"></param>
        /// <returns></returns>
        public static bool Delete(params XElement[] xeFileID)
        {
            bool isOK = false;
            try
            {
                using (HttpResponseMessage res = string.Format("File/Delete").HttpPost(xeFileID))
                {
                    ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                    {
                        isOK = true;
                    });
                }
            }
            catch (Exception ex)
            {
                Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("删除文件失败", ex.Message);
                error.Show();
            }
            return isOK;
        }
        /// <summary>
        /// 用于删除指定服务器的文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="xeFileID"></param>
        /// <returns></returns>
        public static bool Delete(string url, params XElement[] xeFileID)
        {
            bool isOK = false;
            try
            {
                using (HttpResponseMessage res = string.Format(url + "GFileMgr/Delete").HttpPost(true, xeFileID))
                {
                    ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                    {
                        isOK = true;
                    });
                }
            }
            catch (Exception ex)
            {
                Twi.COMMON.WPF.ErrorInfo error = new Twi.COMMON.WPF.ErrorInfo("删除文件失败", ex.Message);
                error.Show();
            }
            return isOK;
        }
        #endregion

        #region 图片压缩函数
        /// <summary>
        /// 图片压缩函数
        /// </summary>
        /// <param name="sourceFile">原始图片文件</param>
        /// <param name="quality">质量压缩比</param>
        /// <param name="ouputFile">输出文件名,请用 .jpg 后缀 </param>
        /// <returns>成功返回true，失败则返回false</returns>
        public static bool imageCompress(String sourceFile, long quality, String outputFile)
        {
            try
            {
                long imageQuality = quality;
                Bitmap sourceImage = new Bitmap(sourceFile);
                ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg");
                System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
                myEncoderParameters.Param[0] = myEncoderParameter;

                sourceImage.Save(outputFile, myImageCodecInfo, myEncoderParameters);
                return true;

            }
            catch
            {
                return false;
            }

        }
        #endregion
        #region 获取图片编码信息
        /// <summary>
        /// 获取图片编码信息
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }
        #endregion ImageCodeInfo
    }
}
